package com.ldc.commonlibs.common

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ldc.commonlibs.conf.AppCodeConf
import com.ldc.commonlibs.http.RetrofitClientBase
import kotlinx.coroutines.*

abstract class ViewModelBase : ViewModel() {
    override fun onCleared() {
        super.onCleared()
        viewModelScope.cancel()
    }

    open fun <T> getServer(clazz: Class<T>) =
        getServerByUrl(com.ldc.commonlibs.http.conf.ApiConf.BASE_URL, clazz)

    open fun <T> getServerByUrl(url: String, clazz: Class<T>) =
        RetrofitClientBase.getInstance().createServer(url, clazz)


    //请求数据
    fun <T> launchUi(block: suspend CoroutineScope.() -> RspModel<T>): MutableLiveData<RspModel<T>> {
        val data = MutableLiveData<RspModel<T>>()
        // viewModelScope  默认 是主线程
        viewModelScope.launch {
            try {
                // 切换异步线程
                val r = withContext(Dispatchers.IO) {
                    block()
                }
                data.value = r
            } catch (e: Exception) {
                data.value = RspModel(AppCodeConf.errorCode, "${e.message}")
            }
        }
        return data
    }

    // 请求列表数据
    fun <T> launchListUi(block: suspend CoroutineScope.() -> RspModel<RspPagingModel<T>>): MutableLiveData<RspModel<RspPagingModel<T>>> {
        val data = MutableLiveData<RspModel<RspPagingModel<T>>>()
        viewModelScope.launch {
            // 默认是主线程
            try {
                val r = withContext(Dispatchers.IO) {
                    block()
                }
                data.value = r
            } catch (e: Exception) {
                data.value = RspModel(AppCodeConf.errorCode, "${e.message}")
            }
        }
        return data
    }

}